package com.mlan.userap.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.flyjingfish.openimagelib.OpenImage;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OnKeyboardListener;
import com.mlan.userap.AppConfig;
import com.mlan.userap.LoginActivity;
import com.mlan.userap.MainActivity;
import com.mlan.userap.MyAPP;
import com.mlan.userap.R;
import com.mlan.userap.SplashActivity;
import com.mlan.userap.adapter.ChatMsgAdapter;
import com.mlan.userap.component.Emoji;
import com.mlan.userap.component.EmojiClickListener;
import com.mlan.userap.component.FaceManager;
import com.mlan.userap.component.LoadFace;
import com.mlan.userap.component.MsgListener;
import com.mlan.userap.dialog.VoiceDialog;
import com.mlan.userap.model.ChatGroupInfo;
import com.mlan.userap.model.ChatUser;
import com.mlan.userap.model.MediaInfo;
import com.mlan.userap.model.MsgEntity;
import com.mlan.userap.model.MsgEvent;
import com.mlan.userap.model.MsgInquRequ;
import com.mlan.userap.model.MsgInquResp;
import com.mlan.userap.model.MsgRequ;
import com.mlan.userap.model.MsgFileInfo;
import com.mlan.userap.model.MsgResp;
import com.mlan.userap.model.OpCode;
import com.mlan.userap.model.OssInfo;
import com.mlan.userap.okhttp.ApiResponse;
import com.mlan.userap.okhttp.JsonCallBackData;
import com.mlan.userap.okhttp.OkHttpHelper;
import com.mlan.userap.okhttp.ProgressListener;
import com.mlan.userap.okhttp.UploadHelper;
import com.mlan.userap.untils.AACPlayer;
import com.mlan.userap.untils.CommTool;
import com.mlan.userap.untils.Convert;
import com.mlan.userap.untils.FileUploader;
import com.mlan.userap.untils.LogHelper;
import com.mlan.userap.untils.MediaRecord;
import com.mlan.userap.untils.PermissionHelper;
import com.mlan.userap.widget.EmojiIndicatorView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Response;


public class ChatActivity extends BaseActivity implements View.OnClickListener {

    ChatGroupInfo groupEntity = null;


    public EditText et_content;

    public RecyclerView mRecyclerView;

    public TextView btn_send;

    public ImageView iv_return;

    public TextView tv_groupName;

    public TextView tv_tips;


    public ImageView btn_file;

    public ImageView btn_face;
    public ImageView btn_face_text;

    ImageView btn_to_voice;

    public ImageView btn_to_text;


    public LinearLayout ll_face;

    public LinearLayout ll_more;

    public LinearLayout ll_tips;


    public ViewPager faceViewPager;

    EmojiIndicatorView faceIndicator;

    private Context mContext;
    private ChatMsgAdapter mAdapter;
    LoadFace loadFace;
    private int voice_pressy = 0;
    private int voice_state = 0;
    private VoiceDialog voiceLoading = null;

    private long msgMinTicks = 0;
    private int oldLines = 0;


    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int PICK_ViDEO_REQUEST = 3;
    private static final int CAMERA_REQUEST = 2;
    private static final int CAMERA_PERMISSION_REQUEST = 100;
    private static final int MEDIA_IMAGES_PERMISSION_REQUEST = 101;
    private static final int REQUEST_CODE_FILE_PICKER = 103;

    private ActivityResultLauncher<Intent> cameraLauncher;

    private long curMsgTicks = System.currentTimeMillis();

    private boolean isLoading = false; // 防止重复加载
    private String Tag = "ChatActivity";

    private MediaRecord mediaRecord = null;

    private AACPlayer aacPlayer = null;

    ActivityResultLauncher<String[]> permissionRecode;
    ActivityResultLauncher<String[]> permissionCamera;

    ActivityResultLauncher<String[]> permissionMedia;
    private Uri photoUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_msg);
        InitViewId();

        permissionRecode = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                }
        );
        permissionCamera = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    LogHelper.i("相机权限请求结果: " + result.toString());
                    boolean allGranted = true;
                    for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                        if (!entry.getValue()) {
                            allGranted = false;
                            LogHelper.i("权限被拒绝: " + entry.getKey());
                        }
                    }
                    if (allGranted) {
                        LogHelper.i("所有必要权限已授予");
                        openCamera();
                    } else {
                        LogHelper.i("部分权限被拒绝，但仍尝试打开相机");
                        openCamera();
                    }
                }
        );
        permissionMedia = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                        if (!entry.getValue()) {
                            deniedPermissions.add(entry.getKey());
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        openGallery();
                    }
                }
        );


        ImmersionBar.with(this)
                .statusBarColor(R.color.background_light)
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.black)
                .keyboardEnable(true)
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        if (isPopup) ChangeKeyBoard(1);
                        Log.e("onKeyboardChange", String.valueOf(isPopup));
                    }
                })
                .fitsSystemWindows(true)
                .init();


        cameraLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        LoadCameraPic();
                    } else {
                        Toast.makeText(this, "拍照取消", Toast.LENGTH_SHORT).show();
                    }
                });

        mContext = ChatActivity.this;
        groupEntity = Convert.fromJson(getIntent().getStringExtra("groupInfo"), ChatGroupInfo.class);
        AppConfig.groupId = groupEntity.getGroupId();
        tv_groupName.setText(groupEntity.getGroupName());
        loadFace = LoadFace.newInstance(this, faceViewPager, faceIndicator);
        loadFace.setEmojiClick(new EmojiClickListener() {
            @Override
            public void onEmojiClick(Emoji emoji) {
                int cursorPosition = et_content.getSelectionStart();
                et_content.getText().insert(cursorPosition, emoji.getFaceKey());
            }
        });
        initView();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        layoutManager.setStackFromEnd(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ChatMsgAdapter(this, groupEntity.getGroupType());
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setListener(new MsgListener() {
            @Override
            public void onClick(View v, MsgEntity msg) {
                if (msg.getMsgType() == 3) {
                    if (aacPlayer != null) {
                        if (aacPlayer.GetFileName().equals(msg.getFileInfo().getResname())) {
                            aacPlayer.finished();
                            return;
                        } else {
                            aacPlayer.finished();
                        }
                    }
                    aacPlayer = new AACPlayer(ChatActivity.this, msg.getFileInfo().getResurl(), msg.getFileInfo().getResname());
                    aacPlayer.start(new AACPlayer.PlaybackCallback() {
                        @Override
                        public void onPlayFinished() {
                            aacPlayer = null;
                            v.findViewById(R.id.ani_play).setVisibility(View.GONE);
                            v.findViewById(R.id.item_autoimg).setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onPlayStart() {
                            v.findViewById(R.id.ani_play).setVisibility(View.VISIBLE);
                            v.findViewById(R.id.item_autoimg).setVisibility(View.GONE);
                        }

                        @Override
                        public void onError() {
                            aacPlayer = null;
                        }
                    });
                } else if (msg.getMsgType() == 4) {
                    ArrayList<MsgEntity> msgEntities = new ArrayList<>();
                    for (MsgEntity msgEntity : mAdapter.getList()) {
                        if (msgEntity.getMsgType() == 4) {
                            msgEntities.add(msgEntity);
                        }
                    }
                    int pos = 0;
                    for (int i = 0; i < msgEntities.size(); i++) {
                        if (msg.getMsgId() == msgEntities.get(i).getMsgId()) {
                            pos = i;
                        }
                    }
//在点击时调用（以下以RecyclerView为例介绍）
                    OpenImage.with(ChatActivity.this)
                            //打开大图页面时没有点击的ImageView则用这个
                            .setNoneClickView()
                            //图片的数据
                            .setImageUrlList(msgEntities)
                            //默认展示数据的位置
                            .setClickPosition(pos)
                            //开始展示大图
                            .show();

                } else if (msg.getMsgType() == 2) {
                    ArrayList<MsgEntity> msgEntities = new ArrayList<>();
                    for (MsgEntity msgEntity : mAdapter.getList()) {
                        if (msgEntity.getMsgType() == 2) {
                            msgEntities.add(msgEntity);
                        }
                    }
                    int pos = 0;
                    for (int i = 0; i < msgEntities.size(); i++) {
                        if (msg.getMsgId() == msgEntities.get(i).getMsgId()) {
                            pos = i;
                        }
                    }

//在点击时调用（以下以RecyclerView为例介绍）
                    OpenImage.with(ChatActivity.this)
                            //打开大图页面时没有点击的ImageView则用这个
                            .setNoneClickView()
                            //图片的数据
                            .setImageUrlList(msgEntities)
                            //默认展示数据的位置
                            .setClickPosition(pos)
                            //开始展示大图
                            .show();
                } else {
                    LogHelper.i("onClick: " + msg.getMsgType());
                }
            }

            @Override
            public void onLongClick(View v, MsgEntity msg) {
                LogHelper.i("onLongClick: " + msg.getMsgType());
            }
        });
        // 监听滚动事件，加载更多历史消息
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                if (firstVisibleItemPosition <= 5 && !isLoading) {
                    //  loadHistoryMessage(false);
                }
            }
        });

        mRecyclerView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                hideKeyboard();
            }
            return false;
        });


        loadHistoryMessage(true);
        // 聊天详情按钮点击事件
        ImageView btnInfo = findViewById(R.id.btn_info);
        btnInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatActivity.this, ChatDetailActivity.class);
                intent.putExtra("groupInfo", Convert.toJson(groupEntity, ChatGroupInfo.class));
                startActivity(intent);
            }
        });
    }

    private void loadHistoryMessage(boolean first) {
        if (isLoading) return;
        isLoading = true;
        int limit = 50;
        List<MsgResp> msgList = MyAPP.getApp().getChatDao().getMessagesByGroupId(groupEntity.getGroupId(), curMsgTicks, limit);
        MsgInquRequ msgInqu = new MsgInquRequ(groupEntity.getGroupId(), curMsgTicks, limit);
        long minticks = 0;
        for (MsgResp item : msgList) {
            msgInqu.getMsgIds().add(item.getMsgId());
            if (minticks == 0) {
                minticks = item.getMsgTicks();
            } else {
                minticks = Math.min(minticks, item.getMsgTicks());
            }
        }
        curMsgTicks = minticks;

        for (MsgResp item : msgList) {
            mAdapter.insertEntity(ChangeEntity(item));
        }
        if (first) toBottom();

        msgInqu.setMinTicks(minticks);
        OkHttpHelper.postData("/Chat/MsgList", msgInqu, new JsonCallBackData<MsgInquResp>() {
            @Override
            public void onSuccess(MsgInquResp data) {
                if (data != null && data.getMsgDatas().size() > 0) {
                    updateMessage(data.getMsgDatas(), first);
                }
                isLoading = false;
            }

            @Override
            public void onError(Exception error) {
            }
        });
    }

    private void updateMessage(List<MsgResp> msgList, boolean first) {
        long minticks = 0;
        for (MsgResp item : msgList) {

            if (minticks == 0) {
                minticks = item.getMsgTicks();
            } else {
                minticks = Math.min(minticks, item.getMsgTicks());
            }
        }
        if (minticks < curMsgTicks) curMsgTicks = minticks;

        for (MsgResp item : msgList) {
            mAdapter.insertEntity(ChangeEntity(item));

        }
        new Thread(() -> {
            MyAPP.getApp().getChatDao().insertMessage(msgList);
        }).start();
        if (msgList.size() > 0 && first) toBottom();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppConfig.groupId = "";
    }

    public void InitViewId() {
        et_content = findViewById(R.id.et_content);
        mRecyclerView = findViewById(R.id.chatmsg_listView);
        btn_send = findViewById(R.id.btn_send);
        iv_return = findViewById(R.id.iv_return);
        tv_groupName = findViewById(R.id.tv_groupName);
        tv_tips = findViewById(R.id.et_tips);

        btn_file = findViewById(R.id.btn_multimedia);
        btn_face = findViewById(R.id.btn_face);
        btn_face_text = findViewById(R.id.btn_face_text);
        btn_to_voice = findViewById(R.id.btn_to_voice);
        btn_to_text = findViewById(R.id.btn_to_text);

        ll_face = findViewById(R.id.ll_face);
        ll_more = findViewById(R.id.ll_more);
        ll_tips = findViewById(R.id.ll_tips);
        faceViewPager = findViewById(R.id.face_viewPager);
        faceIndicator = findViewById(R.id.face_indicator);
    }

    public void toBottom() {
        if (mRecyclerView.getAdapter() != null) {
            RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
            int itemCount = mRecyclerView.getAdapter().getItemCount();
            if (layoutManager instanceof LinearLayoutManager && itemCount > 0) {
                ((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(itemCount - 1, 0);
            }
        }

    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        //监听输入框的变化
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (et_content.getText().toString().length() > 0) {
                    btn_send.setVisibility(View.VISIBLE);
                    btn_file.setVisibility(View.GONE);
                } else {
                    btn_send.setVisibility(View.GONE);
                    btn_file.setVisibility(View.VISIBLE);
                }
            }


            @Override
            public void afterTextChanged(Editable editable) {
                if (et_content.getLineCount() != oldLines) {
                    oldLines = et_content.getLineCount();
                    toBottom();
                }
                String text = editable.toString();
                Pattern pattern = Pattern.compile("\\[.*?\\]");
                Matcher matcher = pattern.matcher(text);
                if (matcher.find()) {
                    Log.e(Tag, "setete");
                    FaceManager.getInstance().emojiInput(editable, text);
                }


            }
        });
        iv_return.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        btn_file.setOnClickListener(this);
        btn_face.setOnClickListener(this);
        btn_face_text.setOnClickListener(this);
        btn_to_voice.setOnClickListener(this);
        btn_to_text.setOnClickListener(this);
        mRecyclerView.setOnClickListener(this);

        findViewById(R.id.btn_chat_choose_camera).setOnClickListener(v -> {
            LogHelper.i("相机按钮被点击");
            MyAPP.getApp().getPermissionHelper().requestCameraPermission(this, permissionCamera, () -> {
                LogHelper.i("相机权限已获取，准备打开相机");
                openCamera();
            });
        });

        // 点击从相册选择照片
        findViewById(R.id.btn_chat_choose_image).setOnClickListener(v -> {
            MyAPP.getApp().getPermissionHelper().requestMediaImagesPermission(this, permissionMedia, () -> openGallery());
        });

        findViewById(R.id.btn_chat_choose_voice).setOnClickListener(v -> {
            stype = 0;
            startCallActivity2();
//            if (checkRecordPermission()) {
//                Intent intent = new Intent(this, CallActivity.class);
//                intent.putExtra("groupInfo", Convert.toJson(groupEntity, ChatGroupInfo.class));
//                intent.putExtra("callType", 0);
//                intent.putExtra("stype", 0);
//                startActivity(intent);
//            } else {
//                requestRecordPermission();
//            }
        });

        findViewById(R.id.btn_chat_choose_vedio).setOnClickListener(v -> {
            stype = 1;
            startCallActivity2();
//            Intent intent = new Intent(this, CallActivity.class);
//            intent.putExtra("groupInfo", Convert.toJson(groupEntity, ChatGroupInfo.class));
//            intent.putExtra("callType", 0);
//            intent.putExtra("stype", 1);
//            startActivity(intent);
//            MyAPP.getApp().getPermissionHelper().requestMediaImagesPermission(this, permissionMedia, () -> openGalleryChooseVideo());
        });
        findViewById(R.id.btn_chat_choose_file).setOnClickListener(this);

        //监听录音按下与松开
        ll_tips.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    voice_pressy = (int) event.getY();
                    MyAPP.getApp().getPermissionHelper().requestRecordAudioPermission(this, permissionRecode, () -> VoiceChange(1));
                    break;
                case MotionEvent.ACTION_MOVE:
                    int y = (int) event.getY();
                    if (y < voice_pressy - 100)
                        VoiceChange(2);
                    else
                        VoiceChange(3);
                    break;

                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    int endy = (int) event.getY();
                    if (endy < voice_pressy - 100)
                        VoiceChange(5);
                    else
                        VoiceChange(4);
                    break;
                default:
                    break;
            }
            return true;
        });
    }


    /**
     * @param stype 1开始 2 提示取消 3 提示说话 4 发送  5 取消发送
     */
    public void VoiceChange(int stype) {
        LogHelper.i("VoiceChange=" + stype);
        ;
        if (voice_state != stype) {
            voice_state = stype;
            if (stype == 1) {
                voiceLoading = new VoiceDialog(this);
                voiceLoading.show();
                mediaRecord = new MediaRecord(this);
                mediaRecord.start();
            }
            if (voiceLoading != null) {
                if (stype == 2) {
                    voiceLoading.showState(2);
                }
                if (stype == 3) {
                    voiceLoading.showState(1);
                }
                if (stype == 4 || stype == 5) {
                    voiceLoading.dismiss();
                    MediaInfo mediaInfo = mediaRecord.stop();
                    SendAAC(mediaInfo);
                }
            }

        }
    }
    int stype = 0;
    public void startCallActivity2(){
        if (checkRecordPermission()) {
            Intent intent = new Intent(this, CallActivity.class);
            intent.putExtra("groupInfo", Convert.toJson(groupEntity, ChatGroupInfo.class));
            intent.putExtra("callType", 0);
            intent.putExtra("stype", stype);
            startActivity(intent);
        } else {
            requestRecordPermission();
        }
    }


    /**
     * 隐藏键盘
     */
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0);
    }

    public void showKeyboard() {
        et_content.requestFocus();
        // 显示软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et_content, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 键盘改变
     *
     * @param stype 1 键盘获得焦点  2 键盘失去焦点 3 点表情 4 点+号
     */
    public void ChangeKeyBoard(int stype) {
        if (stype == 1) {
            ll_face.setVisibility(View.GONE);
            ll_more.setVisibility(View.GONE);
            toBottom();
        }
        if (stype == 2) {
            hideKeyboard();
            ll_face.setVisibility(View.GONE);
            ll_more.setVisibility(View.GONE);
        }
        if (stype == 3) {
            if (ll_face.getVisibility() == View.VISIBLE) {
                ll_face.setVisibility(View.GONE);
            } else {
                hideKeyboard();
                loadFace.Show();
                ll_more.setVisibility(View.GONE);
                ll_face.setVisibility(View.VISIBLE);

                et_content.setVisibility(View.VISIBLE);
                ll_tips.setVisibility(View.GONE);
                btn_to_voice.setVisibility(View.VISIBLE);
                btn_to_text.setVisibility(View.GONE);
            }
            toBottom();
        }
        if (stype == 4) {
            if (ll_more.getVisibility() == View.VISIBLE) {
                ll_more.setVisibility(View.GONE);
            } else {
                hideKeyboard();
                ll_face.setVisibility(View.GONE);
                ll_more.setVisibility(View.VISIBLE);
            }
            toBottom();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void msgEvent(MsgEvent event) {
        if (event.code.equals(OpCode.Chat.toString())) {
            mAdapter.addEntity(ChangeEntity((MsgResp) event.data));
            toBottom();
        }
    }

    private MsgEntity ChangeEntity(MsgResp msgResp) {
        MsgEntity addMsg = new MsgEntity();
        addMsg.setMsgId(msgResp.getMsgId());
        addMsg.setUidFrom(msgResp.getUidFrom());
        addMsg.setGroupId(msgResp.getGroupId());
        addMsg.setMsgType(msgResp.getMsgType());
        addMsg.setMsgContent(msgResp.getMsgContent());
        addMsg.setMsgTicks(msgResp.getMsgTicks());
        addMsg.setFileInfo(msgResp.getFileInfo());
        Optional<ChatUser> userFrom = groupEntity.getUserList().stream()
                .filter(q -> q.getUserId() == msgResp.getUidFrom())
                .findFirst();
        if (userFrom.isPresent()) {
            addMsg.setHeadFrom(userFrom.get().getHeadurl());
            addMsg.setNickFrom(userFrom.get().getNick());
        }
        return addMsg;
    }

    private void SendMsg(int msgType, String msgContent, MsgFileInfo reInfo) {
        MsgRequ msgEntity = new MsgRequ();
        msgEntity.setGroupId(groupEntity.getGroupId());
        msgEntity.setMsgType(msgType);
        msgEntity.setMsgContent(msgContent);
        msgEntity.setFileInfo(reInfo);
        OkHttpHelper.postData("/Chat/SendMsg", msgEntity, new JsonCallBackData<MsgResp>() {
            @Override
            public void onSuccess(MsgResp data) {
                // et_content.setText("");
            }

            @Override
            public void onError(Exception error) {
            }
        });
    }

    private void SendMsg(int msgType, String msgContent) {
        SendMsg(msgType, msgContent, null);
    }

    @Override
    public void onClick(View v) {
        int clcId = v.getId();
        LogHelper.i("clc=" + clcId);
        if (clcId == R.id.btn_send) {

            String content = et_content.getText().toString();
            if (content.length() <= 0) {

                CommTool.showToast(mContext, "消息不能为空哟");
                return;
            }
            SendMsg(1, content);
        }
        if (clcId == R.id.btn_face) {
            ChangeKeyBoard(3);
        }
        if (clcId == R.id.btn_face_text) {
            ChangeKeyBoard(3);
        }

        if (clcId == R.id.btn_multimedia) {
            ChangeKeyBoard(4);
        }
        if (clcId == R.id.btn_to_voice) {
            btn_to_voice.setVisibility(View.GONE);
            btn_to_text.setVisibility(View.VISIBLE);
            et_content.setVisibility(View.GONE);
            ll_tips.setVisibility(View.VISIBLE);
            ChangeKeyBoard(2);
        }
        if (clcId == R.id.btn_to_text) {
            btn_to_voice.setVisibility(View.VISIBLE);
            btn_to_text.setVisibility(View.GONE);
            et_content.setVisibility(View.VISIBLE);
            ll_tips.setVisibility(View.GONE);
            ChangeKeyBoard(2);
            showKeyboard();
        }
        if (clcId == R.id.chatmsg_listView) {
            showToast("aaaaa");
            ChangeKeyBoard(2);
        }
        if (clcId == R.id.iv_return) {
            finish();
        }


        if (clcId == R.id.btn_chat_choose_vedio) {

        }
        if (clcId == R.id.btn_chat_choose_voice) {

        }
        if (clcId == R.id.btn_chat_choose_file) {
            openChooseFile();
        }
    }

    private void openChooseFile() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");  // 所有文件类型
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, REQUEST_CODE_FILE_PICKER);
    }

    private boolean hasPermissions(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    // 检查相机权限
    private boolean checkRecordPermission() {
        String[] permissions = {
                android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO,

        };
        return hasPermissions(permissions);
    }

    // 请求媒体图片权限（适配 Android 13+）
    private void requestRecordPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO},
                200);
    }


    // 打开相机
    private void openCamera() {
        LogHelper.i("openCamera 方法被调用");
        try {
            Intent intent = new Intent(this, CameraActivity.class);
            LogHelper.i("准备启动CameraActivity");
            startActivity(intent);
            LogHelper.i("CameraActivity已启动");
        } catch (Exception e) {
            LogHelper.i("启动相机时出错: " + e.getMessage());
            Toast.makeText(this, "启动相机失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


    private boolean isGalleryAppInstalled() {
        PackageManager packageManager = getPackageManager();
        try {
            packageManager.getPackageInfo("com.miui.gallery", 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    private void openVideoSelector(int requestCode) {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("video/*");
//        intent.setPackage("com.miui.gallery"); // 优先小米相册
//
//        Intent wrapperIntent = Intent.createChooser(intent, "Select a Video");
//
//        try {
//            startActivityForResult(wrapperIntent, requestCode);
//        } catch (ActivityNotFoundException e) {
//            Log.e(TAG, "小米相册不可用: " + e.getMessage());
//            // 回退到默认行为
//            Intent fallbackIntent = new Intent(Intent.ACTION_GET_CONTENT);
//            fallbackIntent.setType("video/*");
//            Intent fallbackWrapper = Intent.createChooser(fallbackIntent, "Select a Video");
//            try {
//                startActivityForResult(fallbackWrapper, requestCode);
//            } catch (ActivityNotFoundException fallbackException) {
//                Log.e(TAG, "回退方案失败: " + fallbackException.getMessage());
//                Toast.makeText(this, "无法打开视频选择器", Toast.LENGTH_SHORT).show();
//            }
//        }
    }

    public boolean isXiaomiDevice() {
        String manufacturer = Build.MANUFACTURER.toLowerCase();
        return manufacturer.contains("xiaomi");
    }

    // 打开相册
    private void openGallery() {
        Matisse.from(ChatActivity.this)
                .choose(MimeType.ofImage()) // 选择图片和视频
                .countable(true) // 是否显示数字
                .maxSelectable(1) // 最多选择数量
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size)) // 图片显示大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 屏幕方向
                .thumbnailScale(0.85f) // 缩略图比例
                .imageEngine(new GlideEngine()) // 使用Glide加载引擎
                .forResult(PICK_IMAGE_REQUEST); // 请求码
    }

    // 打开相册
    private void openGalleryChooseVideo() {
        Matisse.from(ChatActivity.this)
                .choose(MimeType.ofVideo()) // 选择图片和视频
                .countable(true) // 是否显示数字
                .maxSelectable(1) // 最多选择数量
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size)) // 图片显示大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 屏幕方向
                .thumbnailScale(0.85f) // 缩略图比例
                .imageEngine(new GlideEngine()) // 使用Glide加载引擎
                .forResult(PICK_ViDEO_REQUEST); // 请求码
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST:
                    LoadCameraPic();
                    break;
                case PICK_IMAGE_REQUEST:
                    if (data != null) {
                        List<Uri> selected = Matisse.obtainResult(data);
                        SendImage(selected.get(0));
                    }
                    break;
                case PICK_ViDEO_REQUEST:
                    if (data != null) {
                        List<Uri> selected = Matisse.obtainResult(data);
                        sendVideo(selected.get(0));
                    }
                    break;
                case REQUEST_CODE_FILE_PICKER:
                    if (data != null) {
                        sendFile(data.getData());
                    }
                    break;
                case 200:
                    startCallActivity2();
                    break;
            }
        }
    }

    public void LoadCameraPic() {
        //            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), photoUri);
//            LogHelper.i("拍照成功"+bitmap.getWidth()+","+bitmap.getHeight());
//            LogHelper.i("开始上传: " + imageUri.getPath());
        loadingShow();
        new UploadHelper().uploadImageFile("/File/UploadImage", photoUri, new ProgressListener() {
            @Override
            public void onProgress(long bytesUploaded, long totalBytes) {
                int progress = (int) (100 * bytesUploaded / totalBytes);
                LogHelper.i("上传进度: " + progress + "%");
            }

            @Override
            public void onResponse(Response response) {
                loadingClose();
                LogHelper.i("上传图片结束: ");
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        LogHelper.i("返回内容: " + result);
                        Type type = new TypeToken<ApiResponse<MsgFileInfo>>() {
                        }.getType();
                        ApiResponse<MsgFileInfo> tresult = Convert.fromJson(result, type);
                        if (tresult != null && tresult.getTag() == 1) {
                            SendMsg(2, "", tresult.getData());
                        }
                    } catch (Exception ex) {
                        LogHelper.i("返回内容Ex: " + ex.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(IOException e) {
                LogHelper.i("上传图片失败: " + e.getMessage());
                loadingClose();
            }
        });

    }


    public void SendAAC(MediaInfo mediaInfo) {
        if (mediaInfo != null && mediaInfo.getTime() > 0) {
            loadingShow();
            File aacFile = new File(mediaInfo.getPath());
            new UploadHelper().uploadVoiceFile("/File/UpLoadVoice", aacFile, mediaInfo.getTime(), new ProgressListener() {
                @Override
                public void onProgress(long bytesUploaded, long totalBytes) {
                    int progress = (int) (100 * bytesUploaded / totalBytes);
                    LogHelper.i("上传进度: " + progress + "%");
                }

                @Override
                public void onResponse(Response response) {
                    loadingClose();
                    if (response.isSuccessful()) {
                        try {
                            String result = response.body().string();
                            LogHelper.i("返回内容: " + result);
                            Type type = new TypeToken<ApiResponse<MsgFileInfo>>() {
                            }.getType();
                            ApiResponse<MsgFileInfo> tresult = Convert.fromJson(result, type);
                            if (tresult != null && tresult.getTag() == 1) {
                                SendMsg(3, "", tresult.getData());
                            }
                        } catch (Exception ex) {
                            LogHelper.i("返回内容Ex: " + ex.getMessage());
                        } finally {
                            if (aacFile != null && aacFile.exists()) aacFile.delete();
                        }
                    }
                }

                @Override
                public void onFailure(IOException e) {
                    loadingClose();
                    if (aacFile != null && aacFile.exists()) aacFile.delete();
                }
            });
        }
    }

    public void SendImage(Uri imageUri) {

        LogHelper.i("开始上传: " + imageUri.getPath());
        loadingShow();
        new UploadHelper().uploadImageFile("/File/UploadImage", imageUri, new ProgressListener() {
            @Override
            public void onProgress(long bytesUploaded, long totalBytes) {
                int progress = (int) (100 * bytesUploaded / totalBytes);
                LogHelper.i("上传进度: " + progress + "%");
            }

            @Override
            public void onResponse(Response response) {
                loadingClose();
                LogHelper.i("上传图片结束: ");
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        LogHelper.i("返回内容: " + result);
                        Type type = new TypeToken<ApiResponse<MsgFileInfo>>() {
                        }.getType();
                        ApiResponse<MsgFileInfo> tresult = Convert.fromJson(result, type);
                        if (tresult != null && tresult.getTag() == 1) {
                            SendMsg(2, "", tresult.getData());
                        }
                    } catch (Exception ex) {
                        LogHelper.i("返回内容Ex: " + ex.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(IOException e) {
                LogHelper.i("上传图片失败: " + e.getMessage());
                loadingClose();
            }
        });


    }

    public void sendVideo(Uri videoUri) {
        LogHelper.i("开始上传: " + videoUri.getPath());
        loadingShow();
        new UploadHelper().uploadImageFile("/File/UploadVideo", videoUri, new ProgressListener() {
            @Override
            public void onProgress(long bytesUploaded, long totalBytes) {
                int progress = (int) (100 * bytesUploaded / totalBytes);
                LogHelper.i("上传进度: " + progress + "%");
            }

            @Override
            public void onResponse(Response response) {
                loadingClose();
                LogHelper.i("上传图片结束: ");
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        LogHelper.i("返回内容: " + result);
                        Type type = new TypeToken<ApiResponse<MsgFileInfo>>() {
                        }.getType();
                        ApiResponse<MsgFileInfo> tresult = Convert.fromJson(result, type);
                        if (tresult != null && tresult.getTag() == 1) {
                            SendMsg(4, "", tresult.getData());
                        }
                    } catch (Exception ex) {
                        LogHelper.i("返回内容Ex: " + ex.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(IOException e) {
                LogHelper.i("上传图片失败: " + e.getMessage());
                loadingClose();
            }
        });


    }

    public void sendFile(Uri videoUri) {
        LogHelper.i("开始上传: " + videoUri.getPath());
        loadingShow();
        new UploadHelper().uploadImageFile("/File/UploadFile", videoUri, new ProgressListener() {
            @Override
            public void onProgress(long bytesUploaded, long totalBytes) {
                int progress = (int) (100 * bytesUploaded / totalBytes);
                LogHelper.i("上传进度: " + progress + "%");
            }

            @Override
            public void onResponse(Response response) {
                loadingClose();
                LogHelper.i("上传图片结束: ");
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        LogHelper.i("返回内容: " + result);
                        Type type = new TypeToken<ApiResponse<MsgFileInfo>>() {
                        }.getType();
                        ApiResponse<MsgFileInfo> tresult = Convert.fromJson(result, type);
                        if (tresult != null && tresult.getTag() == 1) {
                            SendMsg(5, "", tresult.getData());
                        }
                    } catch (Exception ex) {
                        LogHelper.i("返回内容Ex: " + ex.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(IOException e) {
                LogHelper.i("上传图片失败: " + e.getMessage());
                loadingClose();
            }
        });


    }

}